package com.shqcjd.preinstallglass.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.shqcjd.preinstallglass.R;
import com.shqcjd.preinstallglass.api.ApiService;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallglass.model.ResponseData;
import com.shqcjd.preinstallglass.model.pojo.AbnormalBean;
import com.shqcjd.preinstallglass.model.pojo.ImgBean;
import com.shqcjd.preinstallglass.model.pojo.UploadException;
import com.shqcjd.preinstallglass.ui.activity.input.VoiceInputActivity;
import com.shqcjd.preinstallglass.ui.adapter.AbnormalAdapter;
import com.shqcjd.preinstallglass.ui.base.BaseActivity;
import com.shqcjd.preinstallglass.ui.base.BasePresenter;
import com.shqcjd.preinstallglass.util.ToastUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class AbnormalActivity extends BaseActivity {
    @BindView(R.id.rv_abnormal)
    RecyclerView rvAbnormal;
    @BindView(R.id.btn_abnormal)
    Button btnAbnormal;
    @BindView(R.id.et_abnormal)
    TextView etAbnormal;
    @BindView(R.id.tv_dialog_abnormal)
    TextView tvDialogAbnormal;
    @BindView(R.id.sv_bg)
    ScrollView svBg;


    private Context context;
    private AbnormalAdapter abnormalAdapter;
    private List<ImgBean> mList = new ArrayList<>();
    private int prid, tId, epId, eId;
    private String value;
    private final int INPUT_FINISH = 25156;
    private final int CAMERA = 2000;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_abnormal;
    }

    @Override
    protected String getVoiceContent() {
        return "|返回|保存|拍照|输入|删除;";
    }


    @Override
    protected void onVoiceResult(String result) {
        Logger.i("识别结果:"+result);
        switch (result) {
            case "返回":
                finish();
                break;
            case "保存":
//                if(mList.size()>0){
                    loadMultiFile(mList,prid);
//                }else{
//                    Toast.makeText(context, "请选择异常图片", Toast.LENGTH_SHORT).show();
//                }
                break;
            case "拍照":
                RequestLocationAndCallPermission();
                break;
            case "输入":
                Intent it = new Intent(context, VoiceInputActivity.class);
                it.putExtra("str", etAbnormal.getText().toString().trim());
                startActivityForResult(it, INPUT_FINISH);
                break;
            case "删除":
                deletePic(mList.size()-1);
                break;
        }
    }

    @Override
    public void init() {
        super.init();
        prid = getIntent().getIntExtra("prid", -1);
        tId = getIntent().getIntExtra("tId", -1);
        epId = getIntent().getIntExtra("epId", -1);
        eId = getIntent().getIntExtra("eId", -1);
        value = getIntent().getStringExtra("value");
    }

    @Override
    public void initView() {
        super.initView();
        context = this;
        abnormalAdapter = new AbnormalAdapter(mList, context);
        rvAbnormal.setLayoutManager(new GridLayoutManager(context, 5));
        rvAbnormal.setAdapter(abnormalAdapter);
        abnormalAdapter.setOnClickDialogListener(new AbnormalAdapter.setOnClickItemAdapterListener() {
            @Override
            public void onClickAddPic(int pos) {
                RequestLocationAndCallPermission();
            }

            @Override
            public void onClickDeletePic(int pos) {
                deletePic(pos);
            }
        });

        btnAbnormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if(mList.size()>0){
                    loadMultiFile(mList,prid);
//                }else{
//                    Toast.makeText(context, "请选择异常图片", Toast.LENGTH_SHORT).show();
//                }
            }
        });
        etAbnormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(context, VoiceInputActivity.class);
                it.putExtra("str", etAbnormal.getText().toString().trim());
                startActivityForResult(it, INPUT_FINISH);
            }
        });

        if(epId!=-1){
            getAbnormalInfoHttp(tId, epId, eId, value);
        }
    }


    public void RequestLocationAndCallPermission() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
//                            startActivityForResult(new  Intent(MediaStore.ACTION_IMAGE_CAPTURE),CAMERA);
                            Intent intent = new Intent();//跳转拍照 需要把launcher升级到最新
                            intent.setClassName("com.lenovo.newvision.launcher", "com.lenovo.newvision.launcher.ceyes.camera.GlassTakePictureActivity");
                            intent.putExtra("enterType", "THIRD_APP");
                            startActivityForResult(intent, CAMERA);
                        } else {

                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        Bundle bundle = data.getExtras();
//        String scanResult = bundle.getString("data");
//        Logger.i("图片路径:"+scanResult);

        // 如果返回值是正常的话
        if (resultCode == 2000) {//拍照
            // 验证请求码是否一至，也就是startActivityForResult的第二个参数
            switch (requestCode) {
                case CAMERA:
                    Bundle bundle = data.getExtras();
                    String scanResult = bundle.getString("data");
                    saveCameraImage(scanResult);
                    break;
                case INPUT_FINISH:
                    etAbnormal.setText(data.getStringExtra("input_key"));
                    break;
                default:
                    break;
            }
        }
    }

    /** 保存相机的图片 **/
    private void saveCameraImage(String url) {
        Logger.i("图片路径:"+url);
        // 检查sd card是否存在
//        if (!Environment.getExternalStorageState().equals(
//                Environment.MEDIA_MOUNTED)) {
//            return;
//        }
//        // 为图片命名啊
//        String name = System.currentTimeMillis() + ".jpg";
//        Bitmap bmp = (Bitmap) data.getExtras().get("data");// 解析返回的图片成bitmap
//
//        // 保存文件
//        FileOutputStream fos = null;
//        File file = new File("/mnt/sdcard/test/");
//        file.mkdirs();// 创建文件夹
//        String fileName = "/mnt/sdcard/test/" + name;// 保存路径
//
//        try {// 写入SD card
//            fos = new FileOutputStream(fileName);
//            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                fos.flush();
//                fos.close();
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }// 显示图片
        addPic(new ImgBean(url, true));
    }

    public void addPic(ImgBean uri){
        mList.add(uri);
        abnormalAdapter.notifyDataSetChanged();
    }

    public void deletePic(int pos){
        mList.remove(pos);
        abnormalAdapter.notifyDataSetChanged();
    }

    /**
     * 上传多图
     * @param mList
     * @param prid
     */
    private void loadMultiFile(List<ImgBean> mList, Integer prid) {
        //上传图片的时候  把本地图片拿出来上传  然后上传成功之后 把上传成功的图片和网络图片合体
        List<File> files = new ArrayList<>();
        for(int i=0; i<mList.size(); i++){
            if(mList.get(i).isLocal){
                files.add(new File(mList.get(i).url));
            }
        }
        if(files.size()==0){
            List<String> l = new ArrayList<>();
            for(int i=0; i<mList.size(); i++){
                if(!mList.get(i).isLocal){
                    l.add(mList.get(i).url);
                }
            }
            putExceptionInfo(l,prid);
        }else {
            ApiService.uploadMultiImg(files)
                    .compose(RxSchedulersHelper.io_main())
                    .subscribe(new RxObserver<ResponseData<List<String>>>() {
                        @Override
                        public void _onSubscribe(Disposable d) {
                            super._onSubscribe(d);
                            showWaitingDialog("上传图片中");
                        }

                        @Override
                        public void _onNext(ResponseData<List<String>> retData) {
                            if (retData.retCode == 10000) {
                                List<String> list = retData.data;
                                for(int i=0; i<mList.size(); i++){
                                    if(!mList.get(i).isLocal){
                                        list.add(mList.get(i).url);
                                    }
                                }
                                putExceptionInfo(retData.data, prid);
                            } else {
                                ToastUtils.showShort(context, "上传失败");
                            }
                        }

                        @Override
                        public void _onError(String errorMessage) {
                            hideWaitingDialog();
                            ToastUtils.showShort(context, errorMessage);
                        }

                        @Override
                        public void _onComplete() {
                            super._onComplete();
                            hideWaitingDialog();
                        }
                    });
        }
    }

    private void getAbnormalInfoHttp(int task_id, int equipment_id, int equipment_part_item_id, String value) {
        ApiService.getAbnormalInfo(task_id, equipment_id, equipment_part_item_id, value)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<AbnormalBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
//                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<AbnormalBean> responseData) {
                        if (responseData.retCode == 10000) {
                            if(!responseData.data.solution_description.equals("")){
                                tvDialogAbnormal
                                        .setText("常见异常提醒\n● "+responseData.data.solution_description);
                            }
                            if(!responseData.data.exception_description.equals("")){
                                etAbnormal
                                        .setText(responseData.data.exception_description);
                            }
                            if(responseData.data.imgs.size()>0){
                                for(int i=0; i<responseData.data.imgs.size(); i++){
                                    mList.add(new ImgBean(responseData.data.imgs.get(i), false));
                                }
                                abnormalAdapter.notifyDataSetChanged();
                            }
                        } else {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        Toast.makeText(context, "网络连接异常", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    /**
     * 添加或修改巡检异常描述
     * @param data
     * @param prid
     */
    private void putExceptionInfo(List<String> data, Integer prid) {
        UploadException uploadException = new UploadException();
        uploadException.patrol_record_id=prid;
        uploadException.info = etAbnormal.getText().toString();
        uploadException.imgs = data;
        String json = new Gson().toJson(uploadException);

        ApiService.putCheckException(json)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<String>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在上传异常信息");
                    }

                    @Override
                    public void _onNext(ResponseData<String> retData) {
                        if (retData.retCode == 10000) {
                            finish();
                            ToastUtils.showShort(context,"提交成功");
                        } else {
                            ToastUtils.showShort(context,"提交信息失败");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(context,errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });

    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        //重新开启全程录像
//        EventBus.getDefault().post(new RestartVideotapeEvent());
    }
}
